/*** Trigger Name: queryRequestTrigger 
 * Author: Accenture
 * Date: 13-Jun-2011
 * Requirement/Project Name: iFulfill
 * Requirement Description: 
 **/

trigger queryRequestTrigger on Query_Request__c (before insert,before update,after insert, after update) {

    set<Id> ItemIds = new set<id>();
    list<Query_Request__c> ClosedReq = new list<Query_Request__c>();     
    List<Query_Request__c> queryRequestList = new List<Query_Request__c>();    
      if (Trigger.isUpdate){ 
          if(Trigger.isBefore){           
                for(Query_Request__c QR :Trigger.new){     
                     String ownerId=string.valueof(QR.OwnerId);  
                     String oldOwnerId=String.valueof(Trigger.oldMap.get(QR.id).OwnerID);  
                     System.debug('ownerid------'+ownerId);  
                     System.debug('oldOwnerId------------'+oldOwnerId);                         
                    if(ownerId != oldOwnerId && ownerId.startswith(IfullfillTextConstant.OWNERVALUE) && oldOwnerId.startswith(IfullfillTextConstant.QUEUEVALUE)){                          
                        QR.Request_Status__c=IfullfillTextConstant.QUERY_PROGRESS_STATUS; //update req status when user claims req from resoltion team queue
                        queryRequestList.add(QR);                  
                    }
                    if(ownerId != oldOwnerId && ownerId.startswith(IfullfillTextConstant.QUEUEVALUE) && oldOwnerId.startswith(IfullfillTextConstant.OWNERVALUE)){                          
                        QR.Request_Status__c=IfullfillTextConstant.QUERY_OPEN_STATUS; //update req status when user claims req from resoltion team queue
                        queryRequestList.add(QR);                  
                    }
                    if((QR.Request_Status__c == IfullfillTextConstant.QUERY_CLOSED_STATUS || QR.Request_Status__c == IfullfillTextConstant.QUERY_CANCEL_STATUS) && QR.Request_Status__c != Trigger.oldMap.get(QR.id).Request_Status__c)
                        ClosedReq.add(QR);
                }
                iFulfillQueryHandler.updateFIStatus(Trigger.IsInsert,ClosedReq); //Update FI status has to be updated everytime a query req is created or is closed                                                                
                    
           }
      }                               
 
    if(trigger.isInsert && Trigger.isAfter)
     {
        iFulfillQueryHandler.updateFIStatus(Trigger.IsInsert,Trigger.New); //Update FI status has to be updated everytime a query req is created 
        iFulfillQueryHandler.updateOwnerAndFISnapshot(trigger.new); 
    }
    if (Trigger.isInsert && Trigger.isBefore)
    {
        iFulfillQueryHandler.updateQROwnerForOOR(trigger.new);
    } 
 }